/**
 * Copyright (c) 2011 eelpo.com
 * All rights reserved.
 */
package com.eelpo.cmmp.core.wicket.behavior;

import com.eelpo.common.util.BlankUtils;

import org.apache.wicket.AttributeModifier;
import org.apache.wicket.model.Model;

/**
 * <pre>
 * 
 * JavaScript 事件确认
 * 
 * </pre>
 * 
 * @author <a href="mailto:Brian@eelpo.com">汪洪州</a>
 * @since 1.0
 */
public class JavascriptEventConfirmation extends AttributeModifier {

	/**
	 * serialVersionUID
	 */
	private static final long serialVersionUID = -1096884010437875296L;

	public JavascriptEventConfirmation(String msg) {
		this("onclick", msg, true, true);
	}

	public JavascriptEventConfirmation(String msg, boolean enabled) {
		this("onclick", msg, enabled, true);
	}

	public JavascriptEventConfirmation(String event, String msg) {
		this(event, msg, true, true);
	}

	public JavascriptEventConfirmation(String event, String msg, boolean enabled) {
		this(event, msg, enabled, true);
	}

	public JavascriptEventConfirmation(String event, String msg, boolean enabled, boolean addAttributeIfNotPresent) {
		super(event, addAttributeIfNotPresent, new Model<String>(msg));

		setEnabled(enabled);
	}

	@Override
	protected String newValue(String currentValue, String replacementValue) {
		StringBuilder script = new StringBuilder();
		script.append("var conf = confirm('");
		script.append(replacementValue);
		script.append("'); ");
		script.append("if (!conf) return false; ");
		if (BlankUtils.isBlank(currentValue)) {
			script.append(currentValue);
		}
		return script.toString();
	}
}
